package com.controller;

import com.ReturnDTO.ReturnDTO;
import com.entity.User;
import com.service.RegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 注册控制层
 * @author Administrator
 *
 */
@RequestMapping(value = "/register")
@Controller
public class RegistrationController {

  @Autowired
  private RegistrationService registrationService;

  /**
   * 页面跳转
   */
  @RequestMapping(value = "/toRegisterPage")
  public ModelAndView toLoginPage(ModelAndView modelAndView){
    modelAndView.setViewName("/register");
    return modelAndView;
  }

  /**
   * 注册
   */
  @PostMapping
  @ResponseBody
  public ReturnDTO userRegistration(User user){
    //判断用户名是否为空
    if (ObjectUtils.isEmpty(user.getUsername())){
      return ReturnDTO.getReturnDTO(500,"用户名不能为空");
    }
    if (ObjectUtils.isEmpty(user.getPassword())){
      return ReturnDTO.getReturnDTO(500,"密码不能为空");
    }
    //正则表达式判断

    String usr = "/^[a-zA-Z0-9_-]{4,16}$/";
    String pas = "/^[a-z0-9_-]{6,18}$/";
    if (user.getUsername().matches(usr)) {
      return ReturnDTO.getReturnDTO(500,"用户名填写不正确，需字母开头");
    }
    if (user.getPassword().matches((pas))) {
      return ReturnDTO.getReturnDTO(500,"密码填写不正确，需字母开头");
    }

    if (!user.getPassword().equals(user.getValidation())) {
      return ReturnDTO.getReturnDTO(500,"校验码填写不正确");
    }
    ReturnDTO returnDTO = registrationService.register(user);
    return returnDTO;
  }

}


